package com.biboheart.breport.dataset.cell;

import com.biboheart.breport.support.utils.NumberUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

public class BrCellSum implements BrCell {
    private final List<Object> valueList = new ArrayList<>();

    @Override
    public void addValue(Object value) {
        valueList.add(value);
    }

    @Override
    public Object getValue() {
        if (valueList.isEmpty()) {
            return null;
        }
        BigDecimal sumDecimal = BigDecimal.ZERO;
        Class<? extends Number> clazz = null;
        for (Object val : valueList) {
            Class<? extends Number> _clazz = NumberUtils.getNumberClass(val);
            if (null == _clazz) {
                continue;
            }
            if (null == clazz) {
                clazz = _clazz;
            } else if (clazz.isAssignableFrom(Integer.class) && _clazz.isAssignableFrom(Long.class)) {
                clazz = _clazz;
            } else if (_clazz.isAssignableFrom(Double.class)) {
                clazz = _clazz;
            }
            BigDecimal dataValBig = new BigDecimal(val.toString());
            sumDecimal = sumDecimal.add(dataValBig);
        }
        if (null == clazz) {
            return 0;
        }
        return NumberUtils.decimalValue(sumDecimal, clazz);
    }
}
